const { exec } = require('../db/mysql')
const xss = require('xss')
const getList = (author, keyword) => {
  let sql = `select * from blogs where 1=1 `
  if (author) {
    // 去除author中的单引号
    const cleanAuthor = author.replace(/'/g, '') // 记得测试得时候，都用单引号，双引号得逻辑没写，最推荐使用参数化查询，但是exec这个方法没有写params这个参数，就算了
    sql += `and author='${cleanAuthor}' `
  }
  if (keyword) {
    const cleanKeyword = keyword.replace(/'/g, '')
    sql += `and title like '%${cleanKeyword}%' `
  }
  sql += `order by createtime desc;`
  // console.log(sql)
  // 返回 promise
  return exec(sql)
}
const getDetail = (id) => {
  let sql = `select * from blogs where id=${id}`
  return exec(sql).then((rows) => {
    return rows[0]
  })
}
const newBlog = (blogData = {}) => {
  const { title, content, author } = blogData
  const createTime = Date.now()
  const sql = `insert into blogs (title, content, createtime, author) values ('${xss(
    title
  )}', '${xss(content)}', ${createTime}, '${author}')`
  return exec(sql).then((insertData) => {
    return { id: insertData.insertId }
  })
  //id表示新建博客，插入到数据表里面的 id
}
const updateBlog = (id, blogData = {}) => {
  const { title, content } = blogData
  const sql = `update blogs set title='${title}', content='${content}' where id=${id}`
  return exec(sql).then((updateData) => {
    if (updateData.affectedRows > 0) {
      return true
    }
    return false
  })
}
const delBlog = (id, author) => {
  const sql = `delete from blogs where id=${id} and author='${author}'`
  return exec(sql).then((delData) => {
    if (delData.affectedRows > 0) {
      return true
    }
    return false
  })
}
//先返回假数据(格式是正确的)
module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
}
